<template>
	<view class="page">
		<!-- 表单区域 -->
		<view class="form-section">
			<!-- 姓名 -->
			<view class="form-item">
				<view class="label">
					<text class="label-text">姓名</text>
					<text class="required">*</text>
				</view>
				<view class="input-wrapper">
					<input 
						class="input-field"
						v-model="formData.name"
						placeholder="请输入姓名"
						@blur="validateField('name')"
					/>
				</view>
				<view v-if="errors.name" class="error-text">{{ errors.name }}</view>
			</view>
			
			<!-- 手机号码 -->
			<view class="form-item">
				<view class="label">
					<text class="label-text">手机号码</text>
					<text class="required">*</text>
				</view>
				<view class="input-wrapper">
					<input 
						class="input-field"
						v-model="formData.mobile"
						placeholder="请输入手机号码"
						type="number"
						maxlength="11"
						@blur="validateField('mobile')"
					/>
				</view>
				<view v-if="errors.mobile" class="error-text">{{ errors.mobile }}</view>
			</view>
			
			<!-- 身份证号码 -->
			<view class="form-item">
				<view class="label">
					<text class="label-text">身份证号码</text>
					<text class="required">*</text>
				</view>
				<view class="input-wrapper">
					<input 
						class="input-field"
						v-model="formData.idcard"
						placeholder="请输入身份证号码"
						maxlength="18"
						@blur="validateField('idcard')"
					/>
				</view>
				<view v-if="errors.idcard" class="error-text">{{ errors.idcard }}</view>
			</view>
			
			<!-- 紧急联系人电话 -->
			<view class="form-item">
				<view class="label">
					<text class="label-text">紧急联系人电话</text>
					<text class="required">*</text>
				</view>
				<view class="input-wrapper">
					<input 
						class="input-field"
						v-model="formData.urgentLinker"
						placeholder="请输入紧急联系人电话"
						type="number"
						maxlength="11"
						@blur="validateField('urgentLinker')"
					/>
				</view>
				<view v-if="errors.urgentLinker" class="error-text">{{ errors.urgentLinker }}</view>
			</view>
			
			<!-- 上传人脸照片 -->
			<view class="form-item">
				<view class="label">
					<text class="label-text">上传人脸照片</text>
					<text class="required">*</text>
				</view>
				<view class="upload-section">
					<view 
						class="upload-box" 
						:class="{ 'has-image': formData.faceImgUrl }"
						@click="chooseImage"
					>
						<image 
							v-if="formData.faceImgUrl" 
							:src="formData.faceImgUrl" 
							class="uploaded-image"
							mode="aspectFill"
						/>
						<view v-else class="upload-placeholder">
							<text class="upload-icon">+</text>
						</view>
					</view>
				</view>
				<view v-if="errors.faceImgUrl" class="error-text">{{ errors.faceImgUrl }}</view>
			</view>
		</view>
		
		<!-- 底部按钮 -->
		<view class="bottom-action">
			<button 
				class="submit-btn"
				:class="{ 'loading': submitLoading }"
				@click="handleSubmit"
			>
				<text class="btn-text">{{ submitLoading ? '提交中...' : '立即购买' }}</text>
			</button>
		</view>
		<fui-loading type="col" v-if="loadActive" :isFixed="true" :isMask="true"></fui-loading>
	</view>
</template>

<script setup>
	import { useUserStore } from '@/store/user'
	const userStore = useUserStore()
	import { useUpload } from '@/uni_modules/wot-design-uni'
	const { startUpload, abort, chooseFile, UPLOAD_STATUS } = useUpload()
	/**
	 * ==================== 数据定义 ====================
	 */
	const userInfo = ref(userStore.userInfo);
	// 提交加载状态
	const submitLoading = ref(false)
	const loadActive = ref(false);
	const paramObj = ref({});
	
	// 表单数据
	const formData = ref({
		name: '',           // 姓名
		mobile: '',          // 手机号码
		idcard: '',         // 身份证号码
		urgentLinker: '', // 紧急联系人电话
		faceImgUrl: '',       // 人脸照片
		hasOldFaceImg: 0       // 是否有历史人脸
	})
	
	// 错误信息
	const errors = ref({
		name: '',
		mobile: '',
		idcard: '',
		urgentLinker: '',
		faceImgUrl: ''
	})
	
	/**
	 * ==================== 方法定义 ====================
	 */
	
	/**
	 * 验证单个字段
	 * @param {string} field - 字段名
	 */
	const validateField = (field) => {
		const value = formData.value[field]
		
		// 清空之前的错误信息
		errors.value[field] = ''
		
		switch (field) {
			case 'name':
				if (!value) {
					errors.value.name = '请输入姓名'
				} else if (value.length < 2 || value.length > 10) {
					errors.value.name = '姓名长度在2到10个字符'
				}
				break
				
			case 'mobile':
				if (!value) {
					errors.value.mobile = '请输入手机号码'
				} else if (!/^1[3-9]\d{9}$/.test(value)) {
					errors.value.mobile = '请输入正确的手机号码'
				}
				break
				
			case 'idcard':
				if (!value) {
					errors.value.idcard = '请输入身份证号码'
				} else if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
					errors.value.idcard = '请输入正确的身份证号码'
				}
				break
				
			case 'urgentLinker':
				if (!value) {
					errors.value.urgentLinker = '请输入紧急联系人电话'
				} else if (!/^1[3-9]\d{9}$/.test(value)) {
					errors.value.urgentLinker = '请输入正确的手机号码'
				}
				break
				
			case 'faceImgUrl':
				if (!value) {
					errors.value.faceImgUrl = '请上传人脸照片'
				}
				break
		}
	}
	
	/**
	 * 验证所有字段
	 */
	const validateAllFields = () => {
		validateField('name')
		validateField('mobile')
		validateField('idcard')
		validateField('urgentLinker')
		validateField('faceImgUrl')
		// 检查是否有错误
		return !Object.values(errors.value).some(error => error !== '')
	}
	
	/**
	 * 选择图片
	 */
	const chooseImage = () => {
		uni.chooseImage({
			count: 1,
			success: (res) => {
				const tempFilePath = res.tempFilePaths[0]
				// TODO: 上传图片到服务器
				loadActive.value = true;
				uploadImage(tempFilePath)
			},
			fail: (err) => {
				console.error('选择图片失败:', err)
				uni.showToast({
					title: '选择图片失败',
					icon: 'none',
					duration: 2000
				})
			}
		})
	}
	
	/**
	 * 上传图片到服务器
	 * @param {string} filePath - 图片路径
	 */
	const uploadImage = async (filePath) => {
		const file = {
			url: filePath,
			status: UPLOAD_STATUS.PENDING,
			percent: 0
		}
		startUpload(file, {
			action: `${getApp().globalData.baseUrl}/v4/vip/uploadImgFile`,
			 formData:{
			  accessToken:userInfo.value.authenticationToken
		  },
			onSuccess(res) {
				const data = JSON.parse(res.data);
				if(data.code==0){
					// 设置图片路径
					formData.value.faceImgUrl = data.data.key
					// 清空错误信息
					errors.value.faceImgUrl = '';
			    	loadActive.value = false;
				}
			},
			onError(err) {
				console.log('上传失败', err) 
			    loadActive.value = false;

			},
			onProgress(progress) {
				console.log('上传进度', progress)
			}
		})
	}
	
	/**
	 * 表单提交
	 */
	const handleSubmit = async () => {
		try {
			// 表单验证
			const isValid = validateAllFields()
			if (!isValid) {
				uni.showToast({
					title: '请检查表单信息',
					icon: 'none',
					duration: 2000
				})
				return
			}
			submitLoading.value = true
			const param = {
				...paramObj.value,
				...formData.value,
			}
		// 跳转支付、判断是私教 还是 团体
		if(paramObj.value.classId){ //有值
			uni.redirectTo({
				url: `/pagesA/view/course/pay2?param=${JSON.stringify(param)}`
			})
		}else{
			uni.redirectTo({
				url: `/pagesA/view/course/pay?param=${JSON.stringify(param)}`
			})
		}
		} catch (error) {
			console.error('表单提交失败:', error)
			uni.showToast({
				title: '提交失败，请重试',
				icon: 'none',
				duration: 2000
			})
		} finally {
			submitLoading.value = false
		}
	}
	
	/**
	 * 重置表单
	 */
	const resetForm = () => {
		formData.value = {
			name: '',
			mobile: '',
			idcard: '',
			urgentLinker: '',
			faceImgUrl: ''
		}
		errors.value = {
			name: '',
			mobile: '',
			idcard: '',
			urgentLinker: '',
			faceImgUrl: ''
		}
	}
	
	/**
	 * ==================== 生命周期 ====================
	 */
	
	const getUser = ()=>{
		loadActive.value = true;
		uni.api.getNewFaceImg().then(res => {
		  if (res.code == 0) {
			  console.log(res.data);
			// formData.value = res.data || {}
			// 对象遍历 有值 赋值
			Object.keys(res.data).forEach(key => {
				if (res.data[key]) {
					formData.value[key] = res.data[key]
				}
			})
			formData.value.hasOldFaceImg = res.data?.faceImgUrl?1:0;
			console.log(formData.value);
			
		  }
		  loadActive.value = false;
		});
	}
	/**
	 * 页面挂载完成后的初始化操作
	 */
	onLoad((opt) => {
		const param = JSON.parse(opt.param);
		paramObj.value = param;
		getUser();
	})
	
</script>

<style lang="scss" scoped>
	.page {
		min-height: 100vh;
		background-color: #f3f4fb;
		padding: 30rpx;
		padding-bottom: 120rpx; // 为底部按钮留出空间
	}

	// 表单区域
	.form-section {
		.form-item {
			margin-bottom: 40rpx;
			
			// 标签区域
			.label {
				display: flex;
				align-items: center;
				margin-bottom: 16rpx;
				
				.label-text {
					font-size: 28rpx;
					color: #333;
					font-weight: 500;
				}
				
				.required {
					color: #ff4757;
					font-size: 28rpx;
					margin-left: 4rpx;
				}
			}
			
			// 输入框容器
			.input-wrapper {
				.input-field {
					width: 100%;
					height: 88rpx;
					background-color: #fff;
					border: 2rpx solid #e8e8e8;
					border-radius: 8rpx;
					padding: 0 24rpx;
					font-size: 28rpx;
					color: #333;
					box-sizing: border-box;
					
					&::placeholder {
						color: #ccc;
					}
					
					&:focus {
						border-color: #666;
						outline: none;
					}
				}
			}
			
			// 上传区域
			.upload-section {
				.upload-box {
					width: 200rpx;
					height: 200rpx;
					background-color: #fff;
					border: 2rpx dashed #e8e8e8;
					border-radius: 8rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					transition: all 0.3s ease;
					
					&.has-image {
						border-style: solid;
						border-color: #666;
					}
					
					.uploaded-image {
						width: 100%;
						height: 100%;
						border-radius: 6rpx;
					}
					
					.upload-placeholder {
						.upload-icon {
							font-size: 60rpx;
							color: #ccc;
							font-weight: 300;
						}
					}
				}
			}
			
			// 错误信息
			.error-text {
				font-size: 24rpx;
				color: #ff4757;
				margin-top: 8rpx;
				padding-left: 4rpx;
			}
		}
	}

	// 底部操作区
	.bottom-action {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		padding: 30rpx;
		border-top: 1rpx solid #f0f0f0;
		
		.submit-btn {
			width: 100%;
			height: 88rpx;
			background-color: #000;
			border: none;
			border-radius: 48rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			transition: all 0.3s ease;
			
			&.loading {
				background-color: #666;
			}
			
			&:active {
				background-color: #333;
			}
			
			.btn-text {
				font-size: 32rpx;
				color: #fff;
				font-weight: 500;
			}
		}
	}
</style>